package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.addOrUpdate(article);
        return Result.success();
    }

    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> pb = null;
        try {
            pb = articleService.list(pageNum, pageSize, categoryId, state);
        }
        catch (Exception e){
            e.printStackTrace();
        }
       return Result.success(pb);
    }

    @DeleteMapping("{id}")
    public Result<String> delete(@PathVariable String id) {
        if (id == null || id.isEmpty()) {
            return Result.error("参数错误");
        } else {
            Integer success = articleService.deleteArticleById(id);
            if (success > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        }
    }
}
